package io.renren.modules.app.controller;

import com.sun.corba.se.spi.ior.ObjectKey;
import io.jsonwebtoken.Claims;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.service.ApiCollectService;
import io.renren.modules.app.service.ApiSongService;
import io.renren.modules.app.utils.JwtUtils;
import io.renren.modules.sys.entity.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * 曲库
 *
 * @author wangyi
 * @mail 794651397@qq.com
 * @createdate 2018/3/16 14:41
 **/
@Api(description = "曲库")
@RestController
@RequestMapping("/app")
public class ApiSongController {
    @Autowired
    private ApiSongService apiSongService;
    @Autowired
    private ApiCollectService apiCollectService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取推荐曲集6张（首页）
     *
     * @author wangyi
     * @createdate 2018/3/16 14:43
     **/
    @ApiOperation("获取推荐曲集6张（首页）")
    @PostMapping("recommendSongsetHome")
    public R recommendSongsetHome() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", 1);
        map.put("limit", 6);
        Query query = new Query(map);
        List<SongsetEntity> list = apiSongService.recommendSongset(query);
        return R.ok().put("result", list);
    }

    /**
     * 获取推荐单曲10条
     *
     * @author wangyi
     * @createdate 2018/3/16 15:07
     **/
    @ApiOperation("获取推荐单曲10条（首页）")
    @PostMapping("recommendSongHome")
    public R recommendSongHome() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", 1);
        map.put("limit", 10);
        Query query = new Query(map);
        List<SongEntity> list = apiSongService.recommendSong(query);
        return R.ok().put("result", list);
    }

    /**
     * 获取最新曲集6张（首页）
     *
     * @author wangyi
     * @createdate 2018/3/16 14:43
     **/
    @ApiOperation("获取最新曲集6张（首页）")
    @PostMapping("newSongsetHome")
    public R newSongsetHome() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", 1);
        map.put("limit", 6);
        Query query = new Query(map);
        List<SongsetEntity> list = apiSongService.newSongset(query);
        return R.ok().put("result", list);
    }

    /**
     * 获取最新单曲10条
     *
     * @author wangyi
     * @createdate 2018/3/16 15:07
     **/
    @ApiOperation("获取最新单曲10条（首页）")
    @PostMapping("newSongHome")
    public R newSongHome() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", 1);
        map.put("limit", 10);
        Query query = new Query(map);
        List<SongEntity> list = apiSongService.newSong(query);
        return R.ok().put("result", list);
    }

    /**
     * 获取所有推荐曲集
     *
     * @author wangyi
     * @createdate 2018/3/19 9:42
     **/
    @ApiOperation("*{分页}* 获取所有推荐曲集")
    @PostMapping("recommendSongsetAll")
    public R recommendSongsetAll(int page, int limit) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        Query query = new Query(map);
        List<SongsetEntity> list = apiSongService.recommendSongsetAll(query);
        int count = apiSongService.recommendSongsetAllCount(query);
        PageUtils pageUtil = new PageUtils(list, count, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 获取所有推荐单曲
     *
     * @author wangyi
     * @createdate 2018/3/19 9:44
     **/
    @ApiOperation("*{分页}* 获取所有推荐单曲")
    @PostMapping("recommendSongAll")
    public R recommendSongAll(int page, int limit) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        Query query = new Query(map);
        List<SongEntity> list = apiSongService.recommendSongAll(query);
        int count = apiSongService.recommendSongAllCount(query);
        PageUtils pageUtil = new PageUtils(list, count, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 获取所有最新曲集
     *
     * @author wangyi
     * @createdate 2018/3/19 9:42
     **/
    @ApiOperation("*{分页}* 获取所有最新曲集")
    @PostMapping("newSongsetAll")
    public R newSongsetAll(int page, int limit) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        Query query = new Query(map);
        List<SongsetEntity> list = apiSongService.newSongsetAll(query);
        int count = apiSongService.newSongsetAllCount(query);
        PageUtils pageUtil = new PageUtils(list, count, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 获取所有最新单曲
     *
     * @author wangyi
     * @createdate 2018/3/19 9:44
     **/
    @ApiOperation("*{分页}* 获取所有最新单曲")
    @PostMapping("newSongAll")
    public R newSongAll(int page, int limit) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        Query query = new Query(map);
        List<SongEntity> list = apiSongService.newSongAll(query);
        int count = apiSongService.newSongAllCount(query);
        PageUtils pageUtil = new PageUtils(list, count, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 根据曲集id获取详情和单曲
     *
     * @author wangyi
     * @createdate 2018/3/19 9:47
     **/
    @ApiOperation("根据曲集id获取详情和单曲 *{如果登陆,必须传token}*")
    @PostMapping("songsetDetail")
    public R songsetDetail(Long id) {
        SongsetEntity songsetEntity = apiSongService.songsetInfo(id);
        List<SongEntity> songEntityList = apiSongService.querySongBySongsetId(id);
        HashMap<String,Object> result=new HashMap<>();
        result.put("collect",false);
        result.put("detail",songsetEntity);
        result.put("songList",songEntityList);
        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(jwtUtils.getHeader());
        }
        //token不为空
        if (StringUtils.isNotBlank(token)) {
            Claims claims = jwtUtils.getClaimByToken(token);
            if (claims != null && !jwtUtils.isTokenExpired(claims.getExpiration())) {
                Long userId = Long.parseLong(claims.getSubject());
                HashMap<String, Object> map = new HashMap<>();
                map.put("userId", userId);
                map.put("songsetId", id);
                int count = apiCollectService.songsetCollectCount(map);
                if (count > 0) {
                    result.put("collect",true);
                }
            }
        }
        return R.ok().put("result", result);

    }

    /**
     * 根据曲谱id获取详情
     *
     * @author wangyi
     * @createdate 2018/3/19 12:08
     **/
    @ApiOperation("根据曲谱id获取详情 *{如果登陆,必须传token}*")
//    @Login
    @PostMapping("songDetail")
    public R songDetail(Long id) {
        HashMap<String,Object> result=new HashMap<>();
        SongEntity songEntity = apiSongService.querySongById(id);
        List<SongsetEntity> songsetList=apiSongService.queryGroupSongsetList(id);
        result.put("detail",songEntity);
        result.put("songsetList",songsetList);
        result.put("collect",false);
        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(jwtUtils.getHeader());
        }
        //token不为空
        if (StringUtils.isNotBlank(token)) {
            Claims claims = jwtUtils.getClaimByToken(token);
            if (claims != null && !jwtUtils.isTokenExpired(claims.getExpiration())) {
                Long userId = Long.parseLong(claims.getSubject());
                HashMap<String, Object> map = new HashMap<>();
                map.put("userId", userId);
                map.put("songId", id);
                int count = apiCollectService.songCollectCount(map);
                if (count > 0) {
                    result.put("collect",true);
                }
            }
        }
        return R.ok().put("result",result);
    }

    /**
     * 根据分类筛选曲集
     *
     * @author wangyi
     * @createdate 2018/3/19 10:03
     **/
    @ApiOperation("*{分页}* 根据分类筛选曲集 hard:1不限2新手3初级4中级5高级6挑战 " +
            "style:1不限2流行3古典4轻音乐5动漫6影视 person:1不限2成人3儿童" +
            "scene:1不限2弹唱3练琴 teaching:1不限2经典教材3考级教材")
    @PostMapping("filterSongset")
    public R filterSongset(int page, int limit, Integer hard, Integer style, Integer person, Integer scene, Integer teaching) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        if (hard != null && hard!=1) {
            map.put("hard", hard);
        }
        if (style != null && style!=1) {
            map.put("style", style);
        }
        if (person != null && person!=1) {
            map.put("person", person);
        }
        if (scene != null && scene!=1) {
            map.put("scene", scene);
        }
        if (teaching != null && teaching!=1) {
            map.put("teaching", teaching);
        }
        Query query = new Query(map);
        List<SongsetEntity> list = apiSongService.queryListByClassify(query);
        int count = apiSongService.queryListByClassifyCount(query);
        PageUtils pageUtil = new PageUtils(list, count, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 获取所有热搜词
     *
     * @author wangyi
     * @createdate 2018/3/19 10:16
     **/
    @ApiOperation("获取所有热搜词")
    @PostMapping("getSearchWord")
    public R getSearchWord() {
        List<SearchEntity> list = apiSongService.searchWord();
        return R.ok().put("result", list);
    }

    /**
     * 根据搜索词查找曲谱和曲集
     *
     * @author wangyi
     * @createdate 2018/3/19 10:27
     **/
    @ApiOperation("根据搜索词查找曲谱/曲集/教程")
    @PostMapping("searchByWords")
    public R searchByWords(String keywords) {
        if (StringUtils.isNotBlank(keywords)) {
            HashMap<String,Object> result=new HashMap<>();
            List<SongsetEntity> songsetEntityList = apiSongService.querySongsetByKeyWords(keywords);
            List<SongEntity> songEntityList = apiSongService.querySongByKeyWords(keywords);
            List<TeachEntity> teachEntityList = apiSongService.queryTeachByKeyWords(keywords);
            result.put("songsetList", songsetEntityList);
            result.put("songList", songEntityList);
            result.put("teachList", teachEntityList);
            return R.ok().put("result",result);
        } else {
            throw new RRException("请输入关键词");
        }
    }

    /**
     * 浏览曲谱或视频时存入历史 songId和vedioId 只传一个
     *
     * @author wangyi
     * @createdate 2018/3/19 10:40
     **/
    @ApiOperation("浏览曲谱或视频或教程时存入历史 songId,vedioId,teachId 只传一个 *{需要登陆的token}*")
    @Login
    @PostMapping("addToHistory")
    public R addToHistory(Long songId, Long vedioId ,Long teachId) {
        Long userId = (Long) request.getAttribute("userId");
        HistoryEntity historyEntity = new HistoryEntity();
        historyEntity.setUserId(userId);
        HashMap<String,Object> map=new HashMap<>();
        map.put("userId",userId);
        if (songId != null) {
            map.put("mediaId",songId);
            map.put("type",0);
            historyEntity.setMediaId(songId);
            historyEntity.setType(0);
        }
        if (vedioId != null) {
            map.put("mediaId",vedioId);
            map.put("type",1);
            historyEntity.setMediaId(vedioId);
            historyEntity.setType(1);
        }
        if (teachId != null) {
            map.put("mediaId",teachId);
            map.put("type",2);
            historyEntity.setMediaId(teachId);
            historyEntity.setType(2);
        }
        int count=apiSongService.historyCount(map);
        if(count==0){
            historyEntity.setCreateTime(new Date());
            apiSongService.addToHistory(historyEntity);
        }
        return R.ok();
    }

    /**
     * 获取浏览历史 type:0曲谱 1视频
     *
     * @author wangyi
     * @createdate 2018/3/19 10:55
     **/
    @ApiOperation("获取浏览历史 传回type的意义:0代表曲谱 1代表视频 *{需要登陆的token}*")
    @Login
    @PostMapping("getHistory")
    public R getHistory() {
        Long userId = (Long) request.getAttribute("userId");
        List<HistoryEntity> historyEntityList = apiSongService.getHistory(userId);
        List<HashMap<String, Object>> list = new LinkedList<>();
        for (HistoryEntity historyEntity : historyEntityList) {
            HashMap<String, Object> map = new HashMap<>();
            Integer type = historyEntity.getType();
            if (type == 0) {
                SongEntity songEntity = apiSongService.querySongById(historyEntity.getMediaId());
                if(songEntity!=null){
                    map.put("type", 0);
                    map.put("id", songEntity.getId());
                    map.put("name", songEntity.getName());
                    map.put("hard", songEntity.getHardName());
                    map.put("author", songEntity.getAuthor());
                    map.put("uploadUser", songEntity.getUploadUser());
                    map.put("opern", songEntity.getOpern());
                    map.put("createTime", historyEntity.getCreateTime());
                }
            }
            if (type == 1) {
                VedioEntity vedioEntity = apiSongService.queryVedioById(historyEntity.getMediaId());
                if(vedioEntity!=null){
                    map.put("type", 1);
                    map.put("id", vedioEntity.getId());
                    map.put("name", vedioEntity.getName());
                    map.put("url", vedioEntity.getUrl());
                    map.put("createTime", historyEntity.getCreateTime());
                }
            }
            if(map.size()>0){
                list.add(map);
            }
        }
        return R.ok().put("result", list);
    }

}
